package com.ssj.utils;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    public static DataSource dataSource;
    public static Properties properties=new Properties();
    public static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();

    static {
        try {
            InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(resourceAsStream);
            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
            druidDataSource.setUrl(properties.getProperty("jdbc.url"));
            druidDataSource.setUsername(properties.getProperty("jdbc.username"));
            druidDataSource.setPassword(properties.getProperty("jdbc.password"));
            dataSource=druidDataSource;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
    public static Connection getConnection(){
        try {
            if (threadLocal.get()==null)
                threadLocal.set(dataSource.getConnection());
                return threadLocal.get();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static void close(){
        if (threadLocal.get()!=null){
            try{
                threadLocal.get().close();
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("连接关闭失败");
            }
            threadLocal.set(null);
        }
    }
    public static void rollback(){
        if(threadLocal.get()!=null){
            try{
                threadLocal.get().rollback();
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("回滚失败");
            }
        }

    }
    public static void commit(){
        if (threadLocal.get()!=null){
            try{
                threadLocal.get().commit();
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("提交失败");
            }

        }

    }
    public static void start(){

            try{
                getConnection().setAutoCommit(false);
            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException("开启事务失败");
            }


    }

}
